import sha1 from 'sha1'
import getRawBody from 'raw-body'
import * as util from './util'

export default function (opts, reply) {
  return async function middleware(ctx, next) {
    const token = opts.token
    const {
      signature,
      nonce,
      timestamp,
      echostr
    } = ctx.query
    const str = [token, timestamp, nonce].sort().join('')
    const sha = sha1(str)
    if (ctx.method === 'GET') {
      if (sha === signature) {
        ctx.body = echostr  // scott里面的教程是这样写的
        // return echostr
      } else {
        ctx.body = 'fided'
        // return 'Fail'
      }
    } else if (ctx.method === 'POST') {
      if (sha !== signature) {
        return false
      }
      // console.log(ctx.req)

      const data = await getRawBody(ctx.req, {
        length: ctx.length,
        limit: '1mb',
        encoding: ctx.charset
      })
      console.log(data)
      

      const content = await util.parseXML(data)
      const message = util.formatMessage(content.xml)
      ctx.weixin = message

      await reply.apply(ctx, [ctx, next])

      const replyBody = ctx.body
      const msg = ctx.weixin
      const time = parseInt(new Date().getTime() / 1000, 0) + ''
      console.log(msg)
      console.log(replyBody)
      let xml = util.tpl(replyBody, msg)
      // let xml = `<xml><ToUserName><![CDATA[${msg.FromUserName}]]></ToUserName><FromUserName><![CDATA[${msg.ToUserName}]]></FromUserName><CreateTime>${time}</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[你好]]></Content></xml>`
      
      console.log(`xml`)
      console.log(xml)
      ctx.status = 200
      ctx.type = 'application/xml'
      ctx.body = xml
    }
  }
}


